<?php

class Admin_UserController extends Zend_Controller_Action
{

    private $params;
    
    function init()
    {
        $this->params = $this->getRequest()->getParams();
        $response = $this->getResponse();
        $response->insert('header', $this->view->render('/blocks/header.phtml'));
        $response->insert('left', $this->view->render('/blocks/left.phtml'));
    }

    public function indexAction()
    {
        
    }
    
    public function listAction()
    {

        $order = '';
        $sortField = $this->params['sortField'];
        
        if (isset($sortField)) {
            if ($sortField == 'role') {
                $orderQuery .= 'tu.' . $sortField;
            }else{
                $orderQuery .= 'u.' . $sortField; }
        }
        
        if ($this->params['sortDir'] == 'DESC')
        {
            $sortDir = 'ASC';
        } else {
            $sortDir = 'DESC';
        }

        if (isset($sortField))
            $orderQuery .= ' ' . $this->params['sortDir'];

        $this->view->sortField = $sortField;
        $this->view->sortDir = $sortDir;


        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $messages = $flashMessenger->getMessages();
        $this->view->message = $messages[0];

        $user = new Core_User();
        $users = $user->getAll('', $orderQuery);
        $this->view->users = $users;


        // Set pagination settings
        $currentPageNumber = $this->_getParam('page', 1);
        $itemCountPerPage = 10;
        $pageRange = 5;


        // Create paginator
        $paginator = Zend_Paginator::factory($users);
        $paginator->setItemCountPerPage($itemCountPerPage)
                  ->setCurrentPageNumber($currentPageNumber)
                  ->setPageRange($pageRange);
        
        
        // Create paginator control partial view
        Zend_View_Helper_PaginationControl::setDefaultViewPartial('paginator/paginator.phtml');

        // Assign paginator to view
        $this->view->paginator = $paginator;
    }
    
    public function addAction()
    {
        $formUser = new Forms_User();
        $formUsuarios = $formUser->addUser();
        
        if ($this->getRequest()->isPost()) {
            $values = $this->_request->getPost();
            if ($formUsuarios->isValid($values)) {
                $arrayDatos = array(
                    'user' => $values['formuser'],
                    'id_role' => $values['formrole'],
                    'password' => md5($values['formpassword']),
                    'email' => $values['formemail'],
                );
                $user = new Core_User();
                if ($values['id']) {
                    $arrayDatos['last_edit'] = Zend_Date::now();
                    $user->updateUser($values['id'], $arrayDatos);
                } else {
                    $usersMatch = $user->getAll("user = '".$arrayDatos['user']."' or email = '".$arrayDatos['email']."'");
                    if (empty($usersMatch)){
                        $date = new Zend_Date();
                        $arrayDatos['creation'] = $date->get('YYYY/MM/dd HH:mm:s');
                        $user->insertUser($arrayDatos);
                    }else{
                        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                        $flashMessenger->addMessage('Username or email already used.');
                    }
                }
                $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                $flashMessenger->addMessage('User <b>' . $values['formuser'] . '</b> created.');
                $this->_redirect('admin/user/list');
            } else {
                $this->view->status = 2;
                $this->view->formUser = $formUsuarios;
            }
        } else {
            $this->view->formUser = $formUsuarios;
        }
    }

    public function editAction()
    {

        $userID = $this->params['userID'];
        $user = new Core_User();
        $infoUser = $user->getUserByID($userID);
        $formUser = new Forms_User();
        $formUsuarios = $formUser->addUser($infoUser[0]);
        if ($this->getRequest()->isPost()) {
            $values = $this->_request->getPost();
            if ($formUsuarios->isValid($values)) {
                $arrayDatos = array(
                    'user' => $values['formuser'],
                    'id_role' => $values['formrole'],
                    'password' => md5($values['formpassword']),
                    'email' => $values['formemail'],
                );
                if ($values['id']) {
                    $date = new Zend_Date();
                    $arrayDatos['last_edit'] = $date->get('YYYY/MM/dd HH:mm:s');
                    $user->updateUser($values['id'], $arrayDatos);
                } else {
                    $date = new Zend_Date();
                    $arrayDatos['creation'] = $date->get('YYYY/MM/dd HH:mm:s');
                    $user->insertUser($arrayDatos);
                }

                $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                $flashMessenger->addMessage('User <b>' . $values['formuser'] . '</b> edited.');
                $this->_redirect('admin/user/list');
            } else {
                $this->view->status = 2;
                $this->view->formUser = $formUsuarios;
            }
        } else {
            $this->view->formUser = $formUsuarios;
        }
    }

    public function deleteAction()
    {
        $userID = $this->params['userID'];
        $user = new Core_User();
        $infoUser = $user->getUserByID($userID);
        $username = $infoUser[0]['user'];
        if ($this->getRequest()->isPost()) {
            $values = $this->_request->getPost();
            if (isset($values['submit'])) {
                //$arrayUsuario = $user->deleteUser($userID);
                $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                $flashMessenger->addMessage('User <b>' . $username . '</b> deleted.');
            }
            $this->_redirect('/admin/user/list');
        }else{
            $infoUser = $user->getUserByID($userID);
            $formUser = new Forms_User();
            $formUsuarios = $formUser->deleteUser($infoUser[0]);
            $this->view->formUser = $formUsuarios;
        }
        $this->view->username = $username;
    }
    
    

}